<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 质量问题跟踪 -->
    <div id="base-breadcrumb" style="position: relative; z-index: 1">
      <!-- 搜索 -->
      <searchData :search-data="searchArr" @search="search" />
      <!-- 表格 -->
      <a-card :bordered="false">
        <!--表格-->

        <list-table ref="table" row-key="id" :columns="columns" :request="loadData"
          :statistics-config="{ use: true, statistics, temp }"
          :select-config="{ use: true, type: 'checkbox', rowKey: 'id' }"
          :export-config="{ use: true, select: '质量问题跟踪选中', all: '质量问题跟踪全部', customColumns: customColumns }"
          :isShowCountBar="false">
          <span slot="sort" slot-scope="text, record, index">{{ index + 1 }}</span>
          <span slot="action" slot-scope="text, record">
            <template>
              <!-- 查看关联BIM模型 -->
              <a-tooltip>
                <template slot="title">{{ `${record.modelId ? '已' : '未'}关联BIM模型` }}</template>
                <a-icon @click.stop="handleRelease(record)" type="link"
                  :style="{ color: record.modelId ? '#1890ff' : '#ccc' }" />
              </a-tooltip>
              <a class="ml12" v-btn-permission="buttonPermission[0].value" @click="handleManage(0, record)">查看</a>
                  <a-divider v-btn-permission="buttonPermission[0].value" type="vertical" v-if="!record.isOvertime"></a-divider>
                  <!-- 整改超时不上传资料 -->
              <a @click="uploadDataFn(record)" v-btn-permission="buttonPermission[1].value" v-if="!record.isOvertime">上传资料</a>
            </template>
          </span>
          <div slot="expandedRowRender" slot-scope="record" style="margin: 0">
            <span>整改描述：{{ record.problemRectificationDescription || '暂无' }}</span>
          </div>
          <!-- 汇总 -->
          <div slot="bottom">
            <collapseStatic ref="collapseStatic" :columns-summary="columnsSummary" :tab-list="tabList" :form="queryParam" :switch-summary.sync="switchSummary" :load-count="loadCount" :load-data-summary-api="api" :notExpand="true">
              <template #left="scoped">
                <!-- 汇总信息遍历 -->
                <span v-for="(item, index) in summaryList" :key="item.key">
                  {{ item.name }}
                  <a>
                    <b>{{ scoped.data[item.key] || 0 }}</b>
                  </a>
                  <!-- 最后一条数据不加逗号 -->
                  {{ index != summaryList.length - 1 ? '，' : '' }}
                </span>
              </template>
            </collapseStatic>
            <a-tabs default-active-key="1" @change="handleTabChange">
              <a-tab-pane :key="index" :tab="item.name" :disabled="aTabsDisabled"
                v-for="(item, index) in rectificationStatus"></a-tab-pane>
            </a-tabs>
          </div>
        </list-table>
      </a-card>
    </div>
    <!-- 关联BIM模型弹窗 -->
    <BimRelease ref="bimRelease" :zIndex="950" :destroyOnClose="true" :isRelease="false" :visible.sync="visible" :modelList="modelList" />
    <UploadData :visible.sync="uploadDataVisible" :uploadArr="uploadArr" @uploadSucess="uploadSucess"></UploadData>
  </base-breadcrumb>
</template>

<script>
import OrgTreeSelect from '@/components/OrgTreeSelect'
import Selector from '@/components/Select/Selector'
import { problemRectification, typesLabel } from '@/api/quality/quality' // api
import CollapseStatic from '@/views/quality/components/CollapseStatic' // 汇总
import SelectProjectType from '@/components/Select/SelectProjectType' // 工程类别
import SelectProjectStatus from '@/views/quality/components/SelectProjectStatus' // 项目状态
import BimRelease from '@/components/Dialog/BimRelease' // BIM模型关联
import UploadData from './uploadData' // 上传资料
import { qualityTypeLabel } from '@/api/quality/projectDivision' // api
import cloneDeep from 'lodash.clonedeep' // 深拷贝
const columns = [
  {
    title: '序号',
    dataIndex: 'sort',
    width: 80,
    scopedSlots: { customRender: 'sort' }
  },
  {
    title: '受检单位',
    ellipsis: true,
    dataIndex: 'unitName',
    scopedSlots: { customRender: 'branchCompanyName' }
  },
  // {
  //   title: '项目名称',
  //   ellipsis: true,
  //   dataIndex: 'projectName'
  // },
  {
    title: '问题描述',
    ellipsis: true,
    dataIndex: 'problemDescription'
  },
  {
    title: '分项工程',
    ellipsis: true,
    dataIndex: 'subProject'
  },
  {
    title: '复查人',
    ellipsis: true,
    dataIndex: 'reviewer'
  },
  {
    title: '整改人',
    ellipsis: true,
    dataIndex: 'rectificationPeople'
  },
  {
    title: '整改期限',
    dataIndex: 'rectificationPeriod'
  },
  {
    title: '整改状态',
    dataIndex: 'rectificationStatus'
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '120px',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]
const customColumns = [
  {
    title: '序号',
    dataIndex: 'index'
  },
  {
    title: '受检单位',
    dataIndex: 'unitName'
  },
  // {
  //   title: '项目名称',
  //   dataIndex: 'projectName'
  // },
  {
    title: '问题描述',
    dataIndex: 'problemDescription'
  },
  {
    title: '分项工程',
    dataIndex: 'subProject'
  },
  {
    title: '复查人',
    dataIndex: 'reviewer'
  },
  {
    title: '整改人',
    dataIndex: 'rectificationPeople'
  },
  {
    title: '整改期限',
    dataIndex: 'rectificationPeriod'
  },
  {
    title: '整改状态',
    dataIndex: 'rectificationStatus'
  }
]
export default {
    props: {
    // 显隐控件
    buttonPermission: {   //按钮权限
      type: Array,
      default: () => []
    },
    typeId:{   //类别id
      type: String,
      default: () => ''
    },
    searchArrOne:{
      type: Array,
      default: () => []
    }
  },
  name: 'a' + Date.now(),
  components: {
    CollapseStatic,
    BimRelease,
    UploadData
  },
  data() {
    this.columns = columns
    this.customColumns = customColumns
    return {
      statistics: {}, // b-table统计参数
      visible: false,
      modelList: [],
      // aTabs禁用
      aTabsDisabled: false,
      // 表格加载
      tableLoading: true,
      routePath:'', //刷新当前页面的路由
      rectificationStatus: [], //整改状态
      rectificationStatusCode:null,
      uploadArr:{},
      uploadFile:[],
      queryParam: {
        checkTypeId:''
      }, // 查询参数
      typeList:[],
      searchTypeList:[],
      tabList: [
        {
          key: '0',
          name: '按检查区域统计'
        },
        {
          key: '1',
          name: '按分包统计'
        },
        {
          key: '2',
          name: '按检查人'
        },
        {
          key: '3',
          name: '按整改人'
        },
        {
          key: '4',
          name: '按分公司'
        },
        {
          key: '5',
          name: '按项目'
        }
      ], // 汇总标题
      summaryList: [
        {
          name: '质量整改数',
          key: 'total'
        },
        {
          name: '待整改',
          key: 'stayRectification'
        },
        {
          name: '整改中',
          key: 'rectificationIn'
        },
        {
          name: '待复查',
          key: 'stayReview'
        },
        {
          name: '复查通过',
          key: 'stayPass'
        },
        {
          name: '不合格不整改',
          key: 'unqualified'
        },
        {
          name: '整改超时',
          key: 'overtime'
        },
        {
          name: '整改完成率',
          key: 'rectificationRate'
        }
      ], // 汇总列表
      loadCount: 0,
      switchSummary: '0', // 统计标题
      api: problemRectification,
            // 加载数据方法 必须为 Promise 对象

      temp: () => {
        return (
          <span>
            无风险：{this.statistics.draft || 0}， 审核中：{this.statistics.submitted || 0}， 审核通过：
            {this.statistics.past || 0}， 审核不通过：{this.statistics.rejected || 0}， 未销项：
            {this.statistics.sealDraft || 0}, 已销项：
            {this.statistics.sealPast || 0}
          </span>
        )
      }, // 统计项vNode

      // 表格选中项
      selectedRowKeys: [],
      // 表格复选
      rowSelection: {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys) => {
          this.selectedRowKeys = selectedRowKeys
        }
      },
      uploadDataVisible:false,
    }
  },
  watch: {
    selectedRowKeys: {
      handler(newV) {
        this.selectExport = !(newV.length > 0)
      }
    },
  },
  activated() {
    // typesLabel.getList({ type: 3 }).then((res) => {
    //   if (res.code === 200) {
    //     this.rectificationStatus = [{ name: '所有' }]
    //     this.rectificationStatus = this.rectificationStatus.concat(res.data)
    //   }
    // })
  },
  computed: {
    // 汇总表头
    columnsSummary() {
      return [
        {
          title: ['检查区域', '分包商', '检查人', '整改人', '分公司', '项目'][this.switchSummary],
          dataIndex: 'name',
          ellipsis: true
        },
        {
          title: '整改数',
          dataIndex: 'total',
          ellipsis: true
        },
        {
          title: '待整改数',
          dataIndex: 'stayRectification'
        },
        {
          title: '待复查',
          dataIndex: 'stayReview'
        },
        {
          title: '复查通过',
          dataIndex: 'stayPass'
        },
        {
          title: '不合格不整改',
          dataIndex: 'unqualified'
        },
        {
          title: '整改中',
          dataIndex: 'rectificationIn'
        },
        {
          title: '整改超时',
          dataIndex: 'overtime'
        },
        {
          title: '整改率',
          dataIndex: 'rectificationRate'
        }
      ]
    },
    pubSearchArr(){
      return [
            {name: '受检单位', valueKey: 'searchQuery',type: OrgTreeSelect, },
            {name: '项目状态',type: SelectProjectStatus,valueKey: 'projectStatus'},
            {name: '工程类别',type: SelectProjectType,valueKey: 'constructionTypeIds',showStop:false},
            {name: '质量检查编号',value: 'checkNumber',type: 'input'},
            {name: '问题分类', value: 'problemType',type: 'input'},{name: '检查类型',type: Selector,selectType: '0',attr: { code: '1' },valueKey: 'checkType'},
            {name: '复查人',value: 'reviewer',type: 'input' },
            {name: '检查时间',value: 'checkTime',type: 'dateRange',
            attr: {
              rangeFormat: ['checkTimeStart', 'checkTimeEnd']
            }
        },
          {name: '分项工程',value: 'subProject',type: 'input'},
          {name: '整改期限', value: 'rectificationPeriod',
          type: 'dateRange',
          attr: {
            rangeFormat: ['rectificationPeriodStart', 'rectificationPeriodEnd']
          }
        },
        {name: '整改单位',value: 'rectificationUnit',type: 'input'},
        {name: '检查类别',value: 'checkTypeId',type: 'select',data: this.searchTypeList,}
      ]
    },
    searchArr(){
      if(this.typeId){
        this.pubSearchArr.pop()
      }
      return this.pubSearchArr;
    }
  },
  mounted(){
    this.getCheckType();
    typesLabel.getList({ type: 3 }).then((res) => {
      if (res.code === 200) {
        this.rectificationStatus = [{ name: '所有' }]
        this.rectificationStatus = this.rectificationStatus.concat(res.data)
      }
    })
  },
  methods: {
    async loadData(parameter){
      this.tableLoading = true
        this.aTabsDisabled = true
        this.queryParam.checkTypeId =  this.queryParam.checkTypeId || this.typeId;
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return problemRectification
          .postList(requestParameters)
          .then((res) => {
            this.statistics = res.data
            this.table = res.data
            this.total = res.totalSize
            this.tableLoading = false
            this.aTabsDisabled = false
            return res
          })
          .catch((err) => {
            this.tableLoading = false
            this.aTabsDisabled = false
          })
    },
    //上传资料
    uploadDataFn(record){
       this.uploadDataVisible = true;
       this.uploadArr = record;
    },
    handleTabChange(key) {
      if (this.rectificationStatus[key]?.code === '5') {
        this.queryParam.onlyOvertime = true
      } else {
        this.queryParam.onlyOvertime && delete this.queryParam.onlyOvertime
        this.queryParam.rectificationStatus = this.rectificationStatus[key].id
        this.rectificationStatusCode = this.rectificationStatus[key].id
      }
      this.$refs.table.refresh(true)
      this.loadCount++
    },
    /**
     * 搜索
     */
    search(value) {
      this.queryParam = value
      this.queryParam.rectificationStatus =this.rectificationStatusCode;
      this.$refs.table.refresh(true)
      this.loadCount++
    },
    /**
     * 操作栏
     */
    handleManage(type, record) {
      this.$router.push({
        name: 'proejctProblemRecordInfo',
        query: {
          id: record?.id,
          manageType: '1',
          combine: true
        }
      })
    },
    /**
     * @description: 查看关联的BIM模型
     * @param {*} record：业务对象
     * @return {*}
     */
    handleRelease(record) {
      if (record.modelId) {
        this.modelList = [{ id: record.modelId, modelId: record.modelFileId, version: record.modelFileVersion, modelTitle: record.modelTitle, uuId: [record.bimId?.split('&&&&')?.[1]], subAreaId: record.subAreaId }]
        this.visible = true
      }
    },
    /**
     * 删除记录
     */
    handleDelete(e) {
      let that = this
      that.$confirm({
        title: '温馨提示',
        content: '确认删除？',
        okText: '确认',
        cancelText: '关闭',
        onOk() {
          return problemRectification.remove({ id: e.id }).then((res) => {
            that.$message.success('删除成功！')
            that.$refs.table.loadData()
          })
        }
      })
    },
    //获取检查类别
    getCheckType(){
      qualityTypeLabel({type:56}).then((res)=>{
        if(res.code==200){
          this.typeList = res.data;
          this.typeList.length && this.typeList.map((item)=>{
            item.value=item.id;
            item.label = item.name
          })
        }
        this.searchTypeList = cloneDeep(this.typeList);
      })
    },
    //上传资料成功
    uploadSucess(){
      this.search();
    },
  },
}
</script>


